<template>
  <div>
    <div class="upload">
      <el-form :model="formData" :inline="true" ref="ruleFormRef" :rules="rules">
        <el-form-item prop="content">
          <el-input
              type="text"
              v-model="formData.content"
              placeholder="视频内容:"
              :disabled="disabled"
              style="width: 300px;"
          ></el-input>
        </el-form-item>
        <el-form-item prop="title">
          <el-input type="text" style="width: 200px;" v-model="formData.title" placeholder="视频标题:"
                    :disabled="disabled"/>
        </el-form-item>
        <el-form-item prop="type">
          <el-select
              style="width: 300px;"
              v-model="formData.type"
              placeholder="请选择上传视频的类型"
              :disabled="disabled"
              clearable
          >
            <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button @click="uploadFile" type="primary" :disabled="disabled">上传</el-button>
            <el-button
                v-if="formData.file"
                @click="removeFile"
                style="margin-left: 10px;"
                type="primary"
            >删除
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="file-input">
      <input
          type="file"
          ref="fileInput1"
          class="file"
          @change="onFileChange"
          :disabled="disabled"
      />
      <div v-if="formData.file" class="file-info">
        <span>已选择文件: {{ formData.fileName }}</span>
      </div>
      <div v-else class="file-input-label">
        <span class="tubiao">+</span>
        <span>请选择您所要上传的视频</span>
      </div>
    </div>
    <div class="uploadBottom">
      <div class="bottomBox">
        <span class="bottomTop">视频格式</span>
        <p class="bottomBottom">支持常用格式、推荐使用mp4、webm</p>
      </div>
      <div class="bottomBox">
        <span class="bottomTop">视频大小</span>
        <p class="bottomBottom">视频文件大小不超过1G,时长在10分钟以内</p>
      </div>
      <div class="bottomBox">
        <span class="bottomTop">视频分辨率</span>
        <p class="bottomBottom">分辨率为720p(1280×720)及以上</p>
      </div>
    </div>
  </div>
  <global-upload-modal ref="uploadModal"></global-upload-modal>
</template>

<script setup>
import {ref, onMounted, reactive} from "vue";
import {ElMessage} from "element-plus";
import {reqUserList} from "@/api/home.js";
import axios from "axios";
import {useAlertsStore} from "@/store/modules/home.js";
import {ElLoading} from 'element-plus'
import GlobalUploadModal from '@/components/globalUpload.vue'; // 确保路径正确
let formData = ref({
  userId: "1",
  content: "",
  type: "",
  state: "1",
  title: "",
  file: null,
  fileName: '', // 存储文件名
});
const ruleFormRef = ref(null)
const rules = reactive({
  content: [
    {required: true, message: '请输入', trigger: 'blur'},
  ],
  title: [
    {required: true, message: '请输入', trigger: 'blur'},
  ],
  type: [
    {
      required: true,
      message: '请选择',
      trigger: 'change',
    },
  ],
})
let disabled = ref(false);
let options = ref([]);
let fileInput1 = ref(null);
const uploadPercentage = ref(0)
const store = useAlertsStore()
const uploadFile = async () => {

  if (!store.UserInfo.token) {
    ElMessage.error('请登录后上传')
    return
  }
  let valid = await ruleFormRef.value.validate()
  // 首先，在您的组件的setup函数外定义一个引用来保存ElLoading的实例
  let loadingServiceInstance;

  if (valid && formData.value.file) {
    disabled.value = true;
    // 创建FormData对象并添加文件
    const formData1 = new FormData();
    formData1.append("file", formData.value.file);
    // 添加其他请求参数
    formData1.append("userId", store.UserInfo.user.id);
    formData1.append("title", formData.value.title);
    formData1.append("content", formData.value.content);
    formData1.append("type", formData.value.type);
    formData1.append("state", "1");

    // 创建ElLoading服务实例并保存
    loadingServiceInstance = ElLoading.service({
      lock: true,
      text: '上传中',
      background: 'rgba(0, 0, 0, 0.7)',
    });

    axios
        .post("http://127.0.0.1:9999/video/updata/upload", formData1, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
          onUploadProgress: (progressEvent) => {
            // 更新进度条百分比
            uploadPercentage.value = (progressEvent.loaded / progressEvent.total) * 100;

            // 更新ElLoading服务实例的文本
            // if (loadingServiceInstance) {
            //   console.log(loadingServiceInstance,'-----');
            //   loadingServiceInstance.text = `上传中 ${uploadPercentage.value.toFixed(0)}%`;
            // }
          },
        })
        .then(() => {
          ElMessage({
            message: "上传成功",
            type: "success",
          });
          formData.value = {};
          disabled.value = false;

          // 关闭ElLoading服务实例
          loadingServiceInstance.close();
        })
        .catch((error) => {
          ElMessage({
            message: "上传失败，请稍后重试",
            type: "error",
          });
          disabled.value = false;
          formData.value = {};

          // 关闭ElLoading服务实例
          loadingServiceInstance.close();
        }).finally(() => {
      // 在这里放置上传完成后需要执行的逻辑，无论上传成功还是失败
      disabled.value = false;
      ruleFormRef.value.resetFields();
    });
  } else {
    ElMessage.warning('请填写完成的信息');
  }
};
const MAX_FILE_SIZE = 16 * 1024 * 1024; // 16GB in bytes
const ALLOWED_MIME_TYPES = ['video/mp4', 'video/webm', 'video/ogg']; // 允许的MIME类型
const onFileChange = () => {
  const file = fileInput1.value.files[0];
  if (file) {
    if (file.size > MAX_FILE_SIZE) {
      ElMessage.error('文件大小不能超过1GB');
      return;
    }
    if (!ALLOWED_MIME_TYPES.includes(file.type)) {
      ElMessage.error('不支持的文件类型，推荐使用MP4或WEBM格式');
      return;
    }
    formData.value.file = file;
    formData.value.fileName = file.name;
  } else {
    // 如果没有选择文件，则清空文件信息
    formData.value.file = null;
    formData.value.fileName = '';
  }
};

const removeFile = () => {
  formData.value.file = null;
  formData.value.fileName = '';
  fileInput1.value.value = null; // 清空 input 文件控件
  disabled.value = false
};
onMounted(async () => {
  let res = await reqUserList();
  options.value = res.page.list;
});

</script>
<style scoped lang="less">
/* .file{
    width: 1200px;
    border: 1px solid #fff;
    height: 500px;
  }
  .file::-webkit-file-upload-button {
    opacity: 0;
    pointer-events: none;
  } */
.upload {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: -50px;
  margin-bottom: 15px;

  .el-input {
    width: 25%;
  }
}

.file-input {
  margin-top: -18px;
  position: relative;
  width: 1200px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 500px;
  border-radius: 5px;
  background-color: #fff;
}

.file-input input[type="file"] {
  opacity: 0;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.tubiao {
  font-size: 120px;
}

.file-input-label {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: absolute;
  top: 30%;
  left: 50%;
  transform: translateY(-50%);
  transform: translateX(-50%);
  padding: 8px;
  /* background-color: #f1f1f1; */
  /* border: 1px solid #ccc; */
  border-radius: 4px;
  cursor: pointer;
}

/* .file-input input[type="file"]:focus ~ .file-input-label,
  .file-input input[type="file"]:valid ~ .file-input-label {
    display: none;
  } */
.uploadBottom {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;

  .bottomBox {
    width: 32%;
    height: 70px;
    border-radius: 10px;
    background-color: #ffffff;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .bottomTop {
      font-size: 16px;
      font-weight: 800;
      padding-bottom: 5px;
    }

    .bottomBottom {
      font-size: 12px;
      color: #a8abb2;
    }
  }
}
</style>
